import { h } from "koishi"

export const name = "output-filter"

export function apply(ctx) {
  ctx.on("before-send", async session => {
    session.elements = h.transform(session.elements, {
      text({ content }) {
        const p = content.split(/(?:(?<!\d)|(?<=1\W*9))\W*8\W*9\D*?(?:6\D*?|0?\W*6\D*?0\W*)4(?!\W*[1-9])/g)
        return [p[0]].concat(p.slice(1).flatMap(s => [...h.parse(session.text("lnnbot.filter.replace-bad-number")), s]))
      },
      json(_, children) {
        return children
      },
    })
  })
  ctx.i18n.define("zh-CN", "lnnbot.filter.replace-bad-number", "【【疑似敏感数字】】")

  ctx.platform("qq").on("before-send", async session => {
    session.elements = h.transform(session.elements, {
      text({ content }) {
        return content.replace(/(?<=https?:\/\/)[^\s/]*/g, s => "\u200B" + s.replace(/\./g, ".\u200B"))
      }
    })
    if (!session.isDirect) {
      if (session.elements[0]?.type === "text") session.elements[0].attrs.content = session.elements[0].attrs.content.replace(/^\n+/, "")
      if (h.select(session.elements, "text").some(({ attrs: { content } }) => content.includes("\n"))) session.elements.unshift(h.text("\n"))
    }
  })
}
